﻿namespace PhotoAlbum.Web.Services
{
	using System;
    using System.Linq;
	using System.ServiceModel.DomainServices.EntityFramework;
    using System.ServiceModel.DomainServices.Server;
	using PhotoAlbum.Web;

    public abstract class PhotoAlbumService : LinqToEntitiesDomainService<PhotoAlbumModelContainer>
	{
        protected PhotoAlbumUser PhotoUser { get; private set; }

        public override void Initialize(DomainServiceContext context)
        {
            base.Initialize(context);

            if (this.ServiceContext.User.Identity.IsAuthenticated)
            {
                var username = this.ServiceContext.User.Identity.Name;
                this.PhotoUser = this.ObjectContext.PhotoAlbumUsers.FirstOrDefault(pu => pu.UserName == username);
            }
        }

        protected bool CanUserViewAlbum(Album album)
        {
            if (album.Visibility == AlbumVisibility.Public
                || album.OwnerId == this.PhotoUser.Id)
            {
                return true;
            }
            else
            {
                var invited = album.InvitedUsers.Contains(this.PhotoUser);
                if (invited)
                {
                    return true;
                }

                if (album.Visibility == AlbumVisibility.FrirendsAccess)
                {
                    return album.Owner.Friends.Contains(PhotoUser);
                }

                return false;
            }
        }

        protected Picture GetViewablePicture(int pictureId)
        {
            var picture = this.ObjectContext.Pictures.Include("Album").FirstOrDefault(p => p.Id == pictureId);
            if (picture == null)
            {
                throw new Exception("The picture does not exist.");
            }
            if (!this.CanUserViewAlbum(picture.Album))
            {
                throw new Exception("It is not possible to access this picture.");
            }
            return picture;
        }
	}
}


